var resErr = require('../lib/util.js').resErr;
var strUtil = require('../lib/stringUtil.js');
var async = require('async');
var moment = require('moment');
var DB = require('../lib/db_pg').DB;

exports.dict_list = function(req,res){
  var parent_id = req.param('parent_id');
  var sql_text = "select * from t_sys_dict c where 1 = 1 ";
  var tmp_params = [];
  var db = new DB();
  var i = 1;
  if(parent_id){
    sql_text += " and parent_id = $"+ i++;
    tmp_params.push(parent_id);
  }
  if(req.param("key_name")){
    sql_text += " and key_name like '%" + req.param("key_name") + "%'";
  } 
  if(req.param("key_code")){
    sql_text += " and key_code like '%" + req.param("key_code") + "%'";
  }
  var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
  var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
  if(req.param("sort")){
    sql_text += " order by " + req.param("sort");
    if(req.param("dir")){
      sql_text += " " + req.param("dir");
    }
  }
  db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
    if(err) return resErr(res,err);
    return res.json(result);
  })
}

exports.dict_list_by_keycode = function(req, res) {
  var key_code = req.param('key_code');
  if(!key_code) {
    return resErr(res, 'key_code不能为空！');
  }
  var db = new DB();
  var id, dicts;
  async.waterfall([
    function(cb) {
      var sql = "select id from t_sys_dict where key_code=$1";
      var params = [];
      params.push(key_code);
      db.query(sql, params, function(err, rows) {
        if(err) return cb(err);
        if(rows && rows.length > 0) {
          id = rows[0].id;
          return cb(null);
        } else {
          return cb('无法查找到key_code对应的字典信息');
        }
      })
    },
    function(cb) {
      var sql = "select * from t_sys_dict where parent_id=$1 order by sorder";
      var params = [];
      params.push(id);
      db.query(sql, params, function(err, rows) {
        if(err) return cb(err);
        dicts = rows;
        return cb(null);
      })
    }
  ],function(error){
    if(error) return resErr(res, error);
    return res.json(dicts);
  })
}

//普通树结构
exports.dict_tree = function(req,res){
  var sql_text = "SELECT a.* FROM t_sys_dict a WHERE a.parent_id=0 ORDER BY a.sorder ASC";
  //console.log('resource_tree：'+sql_text);
  var tmp_params = [];
  var db = new DB();
  db.query(sql_text,tmp_params,function(err,datas){
    //console.log(datas);
    if(err) return res.json({success:false,msg:JSON.stringify(err)});
    async.eachSeries(datas,function(item,callback){
      //console.log(item);
      var sql_text2 = "select * from t_sys_dict where parent_id = "  + item.id + " ORDER BY sorder ASC";
      //console.log(sql_text2);
      db.query(sql_text2,[],function(err,sub_datas){
        if(err) return callback(err);
        item.sub_categorys = sub_datas;
        async.eachSeries(sub_datas,function(item3,callback2){
          var sql_text3 = "select * from t_sys_dict where parent_id = "  + item3.id + " ORDER BY sorder ASC";
          db.query(sql_text3,[],function(err,sub_datas_3){
            if(err) return callback2(err);
            item3.sub_categorys = sub_datas_3;
            return callback2(null);
          });
        },function(err){
          if(err) return callback(err);
          return callback(null);
        });
      });
    },function(err){
      if(err) return res.json({success:false,msg:JSON.stringify(err)});
      return res.json(getResourceTree(datas));
    });    
  })
}
//生成树结构数组
function getResourceTree(datas) {
  if(datas) {
    var root_children_list = [];
    for(var i=0;i<datas.length;i++) {
      var childlist = datas[i].sub_categorys;
      var child = {};
      if(childlist) {
        child.id = datas[i].id;
        child.text = datas[i].key_name;
        child.leaf = false;
        child.children = getResourceTree(childlist);
        root_children_list.push(child);
      } else {
        child.id = datas[i].id;
        child.text = datas[i].key_name;
        child.leaf = true;
        root_children_list.push(child);
      }
    }
    return root_children_list;
  } else {
    return null;
  }
}

exports.dict_check = function(req,res) {
  var dict_id = req.param('dict_id');
  var key_code = req.param('key_code');
  var sql = "select count(1) from t_sys_dict where key_code=$1";
  if(dict_id) {
    sql += " and id <> " + dict_id;
  }
  var params = [];
  params.push(key_code);
  var db = new DB();
  db.queryInt(sql,params,function(error, count) {
    if(error) return resErr(res, error);
    if(count > 0) {
      return res.json({'success':true});
    } else {
      return res.json({'success':false});
    }
  });
}

exports.dict_admin_list = function(req,res){
  var sql_text = "select * from t_sys_dict c where 1 = 1 ";
  var tmp_params = [];
  var db = new DB();
  var i = 1;
  if(req.param("dict_id")){
    sql_text += " and dict_id = $" + i++;
    tmp_params.push(req.param("dict_id"));
  }
  if(req.param("dict_cat")){
    sql_text += " and dict_cat = $" + i++;
    tmp_params.push(req.param("dict_cat"));
  }
  if(req.param("dict_key")){
    sql_text += " and dict_key = $" + i++;
    tmp_params.push(req.param("dict_key"));
  }
  var limit = parseInt(req.param("limit"));
  var page  = parseInt(req.param("page"));
  if(req.param("sort")){
    sql_text += " order by " + req.param("sort");
    if(req.param("dir")){
      sql_text += " " + req.param("dir");
    }
  }
  db.queryPage(sql_text,tmp_params, page, limit,function(err,result){
    if(err) return resErr(res,err);
    return res.json(result);
  })
}

exports.dict_edit = function(req,res){
  if(!req.param("id"))  return resErr(res,'字典id不得为空！');
  var key_code = req.param('key_code');
  var old_key_code = null;
  var db = new DB();
  async.waterfall([
    function(cb) {
      var sql = "select key_code from t_sys_dict where id=$1";
      var param = [];
      param.push(req.param("id"));
      db.query(sql, param, function(err, rows) {
          if(err) return cb(err);
          if(rows.length > 0)
              old_key_code = rows[0].key_code;
          return cb(null);
      });
    },
    function(cb) {
      //console.log('old_key_code: '+old_key_code);
      if(old_key_code && old_key_code != key_code) {
        var sql = "select count(1) as counter from t_rule where vendor=$1";
        var param = [];
        param.push(old_key_code);
        db.queryInt(sql, param, function(err, counter) {
            if(err) return cb(err);
            if(counter > 0)
                return cb('已存在积分规则引用，字典编码无法修改！');
            return cb(null);
        });
      } else {
        return cb(null);
      }
    },
    function(cb) {
      var tmp_params = [];
      var date_now = moment().format('YYYY-MM-DD HH:mm:ss');
      sql_text = "update t_sys_dict set key_name = $1,key_code = $2,key_desc = $3,parent_id=$4,sorder=$5,update_at=$6 where id = $7";
      tmp_params.push(req.param("key_name"));
      tmp_params.push(req.param("key_code"));
      tmp_params.push(req.param("key_desc"));
      tmp_params.push(req.param("parent_id"));
      tmp_params.push(req.param("sorder"));
      tmp_params.push(date_now);
      tmp_params.push(req.param("id"));
      db.query(sql_text,tmp_params,function(err,datas){
        if(err) return cb(err);
        return cb(null);
      });
    }
  ],function(error) {
    if(error) return resErr(res,error);
    return res.json({"success":true});
  })
  
}

exports.dict_del = function(req,res){
  if(!req.param("id"))  return resErr(res,'字典id不得为空！');
  if(!req.param("key_code")) return resErr(res, 'key_code不能为空！');
  var key_code = req.param('key_code');
  var db = new DB();
  var flag = false;
  async.waterfall([
    function(cb) {
      var sql = "select count(1) as counter from t_rule where vendor=$1";
      var param = [];
      param.push(key_code);
      db.queryInt(sql, param, function(err, counter) {
          if(err) return cb(err);
          if(counter > 0)
              return cb('已存在积分规则引用，无法删除！');
          return cb(null);
      });
    },
    function(cb) {
      var sql = "select count(1) from t_sys_dict where parent_id=$1";
      var params = [];
      params.push(req.param("id"));
      db.queryInt(sql,params,function(err, count){
        if(err) cb(err);
        if(count > 0) {
          flag = true;
        }
        cb(null);
      });
    },
    function(cb) {
      if(flag) {
        cb(null);
      } else {
        var tmp_params = [];
        var sql_text = "delete from t_sys_dict where id = $1 ";
        tmp_params.push(req.param("id"));
        db.query(sql_text,tmp_params,function(err,datas){
          if(err) cb(res,err);
          cb(null)
        })
      }
    }
  ],function(error){
    if(error) return resErr(res, error);
    if(flag) return resErr(res, "该字典下存在子节点，无法删除！");
    return res.json({"success":true});
  });
  
}

exports.dict_add = function(req,res){
  var db = new DB();
  var params = [];
  var date_now = moment().format('YYYY-MM-DD HH:mm:ss');
  params.push(req.param("key_name") || '');
  params.push(req.param("key_code"));
  params.push(req.param("key_desc"));
  params.push(req.param("parent_id"));
  params.push(req.param("sorder"));
  params.push(date_now);
  params.push(date_now);
  var sql = "INSERT INTO t_sys_dict(key_name, key_code, key_desc, parent_id, sorder, create_at, update_at) VALUES ($1, $2, $3, $4, $5, $6, $7)";
  db.query(sql,params,function(err,datas){
    if(err) return resErr(res,err);
    return res.json({"success":true}); 
  })
}

exports.dict_detail = function(req, res) {
  var id = req.param('id');
  var db = new DB();
  var sql = "select * from t_sys_dict where id=$1";
  var params = [];
  params.push(id);
  db.query(sql, params, function(err, rows) {
    if(err) return resErr(res, err);
    return res.json(rows[0]);    
  })
}